"use strict";
let core, config, logger, client = null, subscriber = null,
    _ = require('lodash'), m = require('redis');
let serviceName = 'redis';
let redis = {
  assert: (error) => {
    if (error) {
      logger.error(error);
      throw '[' + serviceName + '] ' + error;
    }
  },
  init: (name, c) =>  new Promise((callback) => {
    serviceName = name;
    core = c;
    logger = core.getLogger(serviceName);
    config = core.getConfig(serviceName);
    let options = {};
    if (config.password) {
      options.auth_pass = config.password;
    }
    client = m.createClient(config.port || 6379, config.host || '127.0.0.1', options);
    client.on('error', redis.assert);
    client.on('connect', () => {
      client.send_command('config', ['set','notify-keyspace-events','Ex'], () => callback());
    });
  }),
  uninit: () => {
    if (client) {
      client.quit();
    }
  },
  getClient: () => client,
  getSubscriber: () => subscriber ? subscriber: subscriber = client.duplicate(),
  command: (command, args, next) => {
    client.send_command(command, args, (error, value) => {
      if (error) {
        // log only
        logger.error(error);
        value = false;
      }
      if (typeof next === 'function') {
        next(value);
      }
    });
  },
};

module.exports = redis;
